package com.jiawa.train.gateway.config;
import cn.hutool.jwt.JWT;
import com.jiawa.train.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 角色授权过滤器：买家/卖家接口权限控制
 */
@Component
public class RoleAuthFilter implements GlobalFilter, Ordered {

    private static final Logger LOG = LoggerFactory.getLogger(RoleAuthFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        // 只拦截需要角色控制的接口
        if (path.startsWith("/buyer/") || path.startsWith("/seller/")) {
            String token = exchange.getRequest().getHeaders().getFirst("token");
            if (token == null || token.isEmpty()) {
                LOG.info("token为空，拒绝访问");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            JWT jwt = JwtUtil.getJwt(token);
            if (jwt == null) {
                LOG.info("token解析或校验失败，拒绝访问");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            String role = (String) jwt.getPayload("role");
            LOG.info("当前用户角色：{}", role);

            // 授权判断
            if (path.startsWith("/buyer/") && !"buyer".equals(role)) {
                LOG.info("非买家用户，禁止访问/buyer/接口");
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
            if (path.startsWith("/seller/") && !"seller".equals(role)) {
                LOG.info("非卖家用户，禁止访问/seller/接口");
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
        }
        // 其他情况直接放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder(){
        return 1;
    }
}